package com.yuyuan.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yuyuan.api.client.NoticeClient;
import com.yuyuan.api.client.UserClient;
import com.yuyuan.api.domain.EventDTOC;
import com.yuyuan.api.domain.NoticeDTOC;
import com.yuyuan.blog.domain.Event;
import com.yuyuan.blog.domain.dto.CommentDTO;
import com.yuyuan.blog.domain.po.BlogDaily;
import com.yuyuan.blog.domain.po.Comment;
import com.yuyuan.blog.mapper.CommentMapper;
import com.yuyuan.blog.mapper.DailyBlogMapper;
import com.yuyuan.blog.service.ICommentService;
import com.yuyuan.blog.service.ILikeService;
import com.yuyuan.blog.utils.IdGenerator;
import com.yuyuan.blog.utils.MyUtils;
import com.yuyuan.common.domain.Result;
import com.yuyuan.api.domain.UserDTOC;
import com.yuyuan.common.domain.po.User;
import com.yuyuan.common.utils.RedisConstants;
import com.yuyuan.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.yuyuan.blog.utils.CommunityConstant.ENTITY_TYPE_COMMENT;
import static com.yuyuan.blog.utils.CommunityConstant.TOPIC_COMMENT;


/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/5/29
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DailyBlogMapper dailyBlogMapper;

    @Autowired
    private ILikeService likeService;

    @Autowired
    private MyUtils myUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private NoticeClient noticeClient;

    @Override
    public Result comment(CommentDTO commentDTO, Long blogId, Long targetId) {
        Long userId = UserHolder.getUser().getId();
        UserDTOC userDTOC = userClient.selectById(userId);
        //生成Comment对象
        Comment comment = BeanUtil.copyProperties(commentDTO, Comment.class);

        // 触发评论通知事件
        long receiveId;
        String name = userClient.selectById(userId).getName();
        if(targetId == 0){
            // targetId = 0 回复帖主
            receiveId = dailyBlogMapper.selectById(blogId).getUserId();
        } else {
            // 回复targetId
            receiveId = targetId;
        }
        NoticeDTOC noticeDTOC = new NoticeDTOC(idGenerator.nextNoticeId(),blogId,userId,receiveId,LocalDateTime.now(),
                "comment","用户" + name + "在帖子" + blogId + "向您评论:" + comment.getContent());
        Event event = new Event(
                TOPIC_COMMENT,
                UserHolder.getUser().getId(),
                ENTITY_TYPE_COMMENT,
                blogId,
                noticeDTOC,
                "Notice");
        noticeClient.fireEvent(BeanUtil.copyProperties(event, EventDTOC.class));


        comment.set(idGenerator.nextCommentId(),blogId,2,targetId,BeanUtil.copyProperties(userDTOC, User.class));
        //保存数据库
        commentMapper.insert(comment);
        //更新博客数据库评论数量(+1)
        UpdateWrapper<BlogDaily> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", blogId).setSql("comments = comments + 1");
        dailyBlogMapper.update(null, updateWrapper);

        // 缓存分数状态变更帖子id
        redisTemplate.opsForSet().add(RedisConstants.getPostScoreKey(), blogId);

        //返回结果
        return Result.ok("评论成功!");
    }

    @Override
    public Result getPageComment(Long blogId, Long startId) {
        //分页查询传入0时默认读取最新(最迟创建)数据，进行处理
        startId = myUtils.zeroHandler(startId, blogId, "Comment");
        List<Comment> list = null;
        if(startId != 0){
            list = commentMapper.getPageByBlogId(blogId, startId);
            for (Comment comment : list) {
                comment.setIfLike(likeService.checkIfLike(UserHolder.getUser().getId(), blogId));
                comment.handlerImgs();
                if(comment.getTargetId()!=0){
                    comment.setTargetName(userClient.selectById(comment.getTargetId()).getName());
                }
            }
        }
        long len = 0;
        if(list != null) len = list.size();
        //返回结果以及长度
        return Result.ok(list, len);
    }
}
